package com.aconcagua.samples.charts.state.model {
  import flash.events.Event;
  import flash.events.EventDispatcher;
  
  [Event(name="sliderChanged")] 
  public class Slider extends EventDispatcher {
    private var _zoomFrom: Number;
    private var _zoomTo: Number;
    private var _leftBoundary: Date;
    private var _rightBoundary: Date;
    private var _series: Series;

    public function Slider(series: Series) {
      _series = series;
      
      _leftBoundary = series.getElementAt(0).date;
      _rightBoundary = series.getElementAt(series.length - 1).date;
      _zoomFrom = _leftBoundary.time;
      _zoomTo = _rightBoundary.time;
    }

    [Bindable(event="sliderChanged")]
    public function get series(): Series {
      return _series;
    }

    public function pointToTime(pointInTime: Number): Number {
      return _leftBoundary.time + pointInTime;
    }

    public function pointToDate(point: Number): Date {
      return new Date(this.pointToTime(point));
    }

    public function get leftBoundary(): Date {
      return _leftBoundary;
    }
    
    public function get rightBoundary(): Date {
      return _rightBoundary;
    }
 
    [Bindable(event="sliderChanged")]
    public function get zoomFrom(): Date {
      return new Date(_zoomFrom);
    }
    
    [Bindable(event="sliderChanged")]
    public function get zoomTo(): Date {
      return new Date(_zoomTo);
    }
    
    [Bindable(event="sliderChanged")]
    public function get zoomPeriodSpan(): Number {
      return Math.max(0, _zoomTo - _zoomFrom);
    }
    
    [Bindable(event="sliderChanged")]
    public function get totalSpan(): Number {
      return _rightBoundary.time - _leftBoundary.time;
    }
    
    [Bindable(event="sliderChanged")]
    public function get rightPeriodSpan(): Number {
      return Math.max(0, _rightBoundary.time - _zoomTo);
    }

    [Bindable(event="sliderChanged")]
    public function get leftPeriodSpan(): Number {
      return Math.max(0, _zoomFrom - _leftBoundary.time);
    }
    
    [Bindable(event="sliderChanged")]
    public function get leftPeriodSpanPercent(): Number {
      return leftPeriodSpan / totalSpan;
    }

    [Bindable(event="sliderChanged")]
    public function get rightPeriodSpanPercent(): Number {
      return rightPeriodSpan / totalSpan;
    }

    [Bindable(event="sliderChanged")]
    public function get zoomPeriodSpanPercent(): Number {
      return zoomPeriodSpan / totalSpan;
    }
    
    public function zoom(timeFrom: Number, timeTo: Number): void {
      _zoomFrom = timeFrom;
      _zoomTo = timeTo;
    }
  }
}